#!/usr/bin/env python
# -*- coding: utf-8 -*-
#

import time

from celtuce.event import Event,OP_INSERT,OP_ERASE,OP_FIND, OP_TEST_ECHO

import simplejson

encode = simplejson.dumps
decode = simplejson.loads

from celtuce.help import logging

logger = logging.getLogger('codec.json')


class Tree(object):
    def __init__(self, name, childTrees=None):
        self.name = name
        if childTrees is None:
            childTrees = []
        self.childTrees = childTrees

def encode_tree(obj):
    if not isinstance(obj, Tree):
        raise TypeError("%r is not JSON serializable" % (o,))

    return obj.__dict__

c1 = Tree("c1")
c2 = Tree("c2") 
t = Tree("t",[c1,c2])

print  simplejson.dumps(t, default=encode_tree)



print encode( 'abc' )
print encode( ['abc',] )
print encode( {1:'abc'})

r = Event()
print encode(r)

request = Event()
request.op = OP_TEST_ECHO
request.body = ('test.codec', 'codec-key', 'x' * 100, int(time.time() * 1000))
request.request_id = 'json.1234567890'

encoded = encode( request )
logger.info('ENCODED : %s', encoded)
decoded = decode( encoded )
print repr(request)
print repr(decoded)
print decoded.body
list = [ decoded.body[i] for i in range(len(decoded.body)) ]
print 'body-list',list
assert request == decoded
print


# test codec performance
time_start = time.time()
times = 10000
for i in xrange(times) :
    encoded = encode( request )
    decoded = decode( encoded )
time_last = time.time() - time_start    
tps = times / time_last
logger.info('test json-codec %d times last %.2f seconds, tps=%.2f', times, time_last, tps)


